package com.example.utgardtutorial1.client;


import com.example.utgardtutorial1.mapper.OpcPhase2Mapper;
import com.example.utgardtutorial1.service.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.IJIUnsigned;
import org.jinterop.dcom.core.JIVariant;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.*;
import org.openscada.opc.lib.da.browser.Branch;
import org.openscada.opc.lib.da.browser.FlatBrowser;
import org.openscada.opc.lib.da.browser.Leaf;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Component
public class OpcClientGen2 {
    @Autowired
    OpcPhase2Mapper opcPhase2Mapper;
    @Autowired
    OpcPhase2Service opcPhase2Service;

    Map<String,Object> stringObjectMap = new HashMap<>();

    //津滨

    @SneakyThrows
    //@Scheduled(cron = "0 */3 * * * ?")
    //@PostConstruct
    public void createClientsZhsc1() throws InterruptedException {

        Server opcDaClient;
        // 连接信
        final ConnectionInformation ci = new ConnectionInformation();
        //ci.setHost("192.168.197.129");         // 本机IP
        ci.setHost("192.168.7.23");         // 本机IP
        ci.setDomain("");                  // 域，为空就行
        ci.setUser("administrator");             // 本机上自己建好的用户名
        ci.setPassword("admin");
        ci.setProgId(null);

        // 使用KEPServer的配置
        ci.setClsid("19d98a61-b3ca-4143-0088-35464d714ea0"); // KEPServer的注册表ID，可以在“组件服务”中查到

        List<String> stringList =opcPhase2Mapper.selectOpcItems();

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        opcDaClient = new Server(ci, executor);

        AutoReconnectController controller = new AutoReconnectController(opcDaClient);
        AccessBase accessBase = new SyncAccess(opcDaClient, 60 * 1000);
        try {
            controller.connect();

            try {
/*                try {
                    opcDaClient.connect();
                } catch (AlreadyConnectedException alreadyConnectedException) {

                }*/
            } catch (BeanCreationException beanCreationException) {
                System.out.println("false_________");
            }

            Integer a = 0;

            for (String itemId : stringList) {
                accessBase.addItem(itemId, new DataCallback() {
                    @Override
                    public void changed(Item item, ItemState itemState) {

                        JIVariant value1 = itemState.getValue();
                        //test.setCreatTime(DateTime.now());
                        try {
                            String values = convertValueToString(value1);
                            if (values.equals("")){
                                values = null;
                            }
                            //test.setValue(values);
                            stringObjectMap.put(itemId,values);
                            //System.out.println(values);
                        } catch (JIException e) {
                            e.printStackTrace();
                        }
                        //testService.save(test);
                    }
                });
            }
            //accessBase.bind();
/*            while (true) {
                accessBase.bind();
                Thread.sleep(60 * 1000);
                //accessBase.unbind();
            }*/
        } catch (final JIException e) {
            System.out.println(String.format("%08X: %s", e.getErrorCode(), opcDaClient.getErrorMessage(e.getErrorCode())));
            if (null != opcDaClient) {
                accessBase.unbind();
                controller.disconnect();
                createClientsZhsc1();
            }
        }
    }

    private void dumpFlat(final FlatBrowser browser)
            throws IllegalArgumentException, UnknownHostException, JIException {
        for (String name : browser.browse()) {
            System.out.println(name);
        }
    }

    @Scheduled(cron = "0 */3 * * * ?")
    private void saveDaguhe(){
        Map<String,Object> objectMap = stringObjectMap;
        for (String key : objectMap.keySet()){
            if (!ObjectUtils.isEmpty(objectMap.get(key))) {
                if (objectMap.get(key).toString().equals("false")) {
                    objectMap.put(key, 0);
                }
                if (objectMap.get(key).toString().equals("true")) {
                    objectMap.put(key, 1);
                }
            }
        }
        System.out.println("opc2");
        //opcPhase2Service.saveMap(objectMap);
    }


    private static String printTab(int level) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < level; i++) {
            sb.append("\t");
        }
        return sb.toString();
    }

    /**
     * 打印Item
     *
     * @param leaf
     */
    private static void dumpLeaf(final Leaf leaf, final int level) {
        System.out.println(printTab(level) + "Leaf: " + leaf.getName() + ":"
                + leaf.getItemId());
    }

    /**
     * 打印Group
     *
     * @param branch
     */
    private static void dumpBranch(final Branch branch, final int level) {
        System.out.println(printTab(level) + "Branch: " + branch.getName());
    }

    public String convertValueToString(JIVariant value) throws JIException {
        String result = "";
        int type = value.getType();
        if (type == JIVariant.VT_I4) {
            int n = value.getObjectAsInt();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_UI4) {
            IJIUnsigned n = value.getObjectAsUnsigned();
            result = String.valueOf(n.getValue().intValue());
        }
        if (type == JIVariant.VT_R4) {
            float n = value.getObjectAsFloat();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_BOOL) {
            boolean n = value.getObjectAsBoolean();
            result = String.valueOf(n);
        }

        if (type == JIVariant.VT_R8) {
            double n = value.getObjectAsDouble();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_I2) {
            short n = value.getObjectAsShort();
            result = String.valueOf(n);
        }
        if (type == JIVariant.VT_UI2) {
            IJIUnsigned n = value.getObjectAsUnsigned();
            result = String.valueOf(n.getValue().shortValue());
        }
        if (type == JIVariant.VT_I1) {
            char n = value.getObjectAsChar();
            result = String.valueOf(n);
        }
        return result;
    }
}
